#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QRegularExpression>
#include <QDateTime>
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QValueAxis>
#include <csignal>  // 添加这个头文件
#include <QNetworkInterface>  // 网络接口相关
#include <QHostAddress>       // IP地址处理
#include <QDebug>

// 实现报警推送方法
void MainWindow::checkAllAlarms()
{
    QDateTime now = QDateTime::currentDateTime();
    auto alarms = alarmStatus.allAlarms();

    LOG_ALARM("Starting alarm check...");

    for (auto it = alarms.begin(); it != alarms.end(); ++it) {
        QString sensorName = it.key();
        double currentValue = getCurrentValue(sensorName);
        LOG_ALARM(QString("Checking %1: Current=%2, Min=%3, Max=%4")
                      .arg(sensorName)
                      .arg(currentValue)
                      .arg(it.value()->minThreshold)
                      .arg(it.value()->maxThreshold));

        if (it.value()->checkAlarm(currentValue, now)) {
           LOG_ALARM(QString("Alarm triggered for %1! Current value %2 is out of range [%3,%4]")
                          .arg(sensorName)
                          .arg(currentValue)
                          .arg(it.value()->minThreshold)
                          .arg(it.value()->maxThreshold));
            sendAlarmToServer(sensorName);
        }
    }

    checkAlarmRecovery();
    //alarmStatus.ccd1.isAlarming = true;
    updateAlarmUI();

    LOG_ALARM("Alarm check completed");
}
/*
void MainWindow::checkAllAlarms()
{
    bool hasAlarm = false;

    for (auto& [name, alarm] : alarmStatus.allAlarms()) {
        double currentValue = getCurrentValue(name);
        alarm->currentValue = currentValue;

        if (currentValue < alarm->minThreshold || currentValue > alarm->maxThreshold) {
            if (!alarm->isAlarming) {
                alarm->isAlarming = true;
                sendAlarmToServer(name);
                hasAlarm = true;
            }
        } else if (alarm->isAlarming) {
            alarm->isAlarming = false;
            sendRecoveryToServer(name);
        }
    }

    // 更新全局状态
    ui->labelGlobalAlarm->setText(hasAlarm ? "ALARM" : "NORMAL");
    ui->labelGlobalAlarm->setStyleSheet(
        QString("background-color: %1; color: white;").arg(hasAlarm ? "red" : "green"));
}*/

void MainWindow::sendAlarmToServer(const QString& alarmName)
{
    // 准备报警信息
    QString status = QString("[%1]    %2 报警: 当前值 %3 (范围: %4~%5)")
                         .arg(QDateTime::currentDateTime().toString("yyyy-MM-ddThh:mm:ss.zzz"))
                         .arg(alarmName)
                         .arg(alarmStatus.allAlarms()[alarmName]->currentValue)
                         .arg(alarmStatus.allAlarms()[alarmName]->minThreshold)
                         .arg(alarmStatus.allAlarms()[alarmName]->maxThreshold);

    // 显示在界面
    ui->alarmInfoText->append(status);
    QNetworkRequest request;
    request.setUrl(QUrl(ConfigManager::instance().alertServerUrl()));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    QJsonObject alarmData;
    alarmData["status"] = 0; // 异常状态
    alarmData["module"] = getModuleCode(alarmName);
    alarmData["reason"] = getAlarmReason(alarmName);
    alarmData["value"] = alarmStatus.allAlarms()[alarmName]->currentValue;
    alarmData["timestamp"] = QDateTime::currentDateTime().toString(Qt::ISODate);

    QNetworkReply* reply = m_networkManager->post(
        request, QJsonDocument(alarmData).toJson());

    connect(reply, &QNetworkReply::finished, [reply]() {
        if (reply->error() != QNetworkReply::NoError) {
            qDebug() << "Alarm POST failed:" << reply->errorString();
        }
        reply->deleteLater();
    });
}

void MainWindow::checkAlarmRecovery()
{
    QDateTime now = QDateTime::currentDateTime();
    auto alarms = alarmStatus.allAlarms();

    for (auto it = alarms.begin(); it != alarms.end(); ++it) {
        auto alarm = it.value();
        double currentValue = getCurrentValue(it.key());

        // 检查是否恢复正常范围
        bool isInRange = (currentValue >= alarm->minThreshold &&
                          currentValue <= alarm->maxThreshold);

        if (alarm->isAlarming && isInRange) {
            // 恢复正常状态
            alarm->isAlarming = false;
            alarm->thresholdExceeded = false;
            sendRecoveryToServer(alarm->alarmName);

            // 可选：记录恢复日志
            LOG_ALARM(QString("%1 恢复正常 (当前值: %2)")
                          .arg(alarm->alarmName)
                          .arg(currentValue));
        }
    }
}

void MainWindow::logAlarms() {
    auto now = QDateTime::currentDateTime();
    auto alarms = alarmStatus.allAlarms();

    for (auto it = alarms.begin(); it != alarms.end(); ++it) {
        if (it.value()->isAlarming) {
            QString duration = QString::number(it.value()->alarmStartTime.secsTo(now));
            LOG_ALARM(QString("%1 Alarm confirmed, exceeding the threshold for %2 seconds")
                          .arg(it.key())
                          .arg(duration));
        }
        else if (it.value()->thresholdExceeded) {
            QString duration = QString::number(it.value()->alarmStartTime.secsTo(now));
            LOG_ALARM(QString("%1Warning - Exceeding the threshold has lasted %2 seconds")
                          .arg(it.key())
                          .arg(duration));
        }
    }
}

void MainWindow::initializeAlarmThresholds()
{
    // 温度报警
    alarmStatus.ccd1.alarmName = "CCD1";
    alarmStatus.ccd1.minThreshold = ConfigManager::instance().ccd1MinTemp();
    alarmStatus.ccd1.maxThreshold = ConfigManager::instance().ccd1MaxTemp();
    alarmStatus.ccd2.alarmName = "CCD2";
    alarmStatus.ccd2.minThreshold = ConfigManager::instance().ccd2MinTemp();
    alarmStatus.ccd2.maxThreshold = ConfigManager::instance().ccd2MaxTemp();
    alarmStatus.ccd3.alarmName = "CCD3";
    alarmStatus.ccd3.minThreshold = ConfigManager::instance().ccd3MinTemp();
    alarmStatus.ccd3.maxThreshold = ConfigManager::instance().ccd3MaxTemp();
    alarmStatus.ccd4.alarmName = "CCD4";
    alarmStatus.ccd4.minThreshold = ConfigManager::instance().ccd4MinTemp();
    alarmStatus.ccd4.maxThreshold = ConfigManager::instance().ccd4MaxTemp();

    alarmStatus.base1.alarmName = "BASE1";
    alarmStatus.base1.minThreshold = ConfigManager::instance().base1MinTemp();
    alarmStatus.base1.maxThreshold = ConfigManager::instance().base1MaxTemp();
    alarmStatus.base2.alarmName = "BASE2";
    alarmStatus.base2.minThreshold = ConfigManager::instance().base2MinTemp();
    alarmStatus.base2.maxThreshold = ConfigManager::instance().base2MaxTemp();

    alarmStatus.absorbCold.alarmName = "absorbCold";
    alarmStatus.absorbCold.minThreshold = ConfigManager::instance().absorbColdMinTemp();
    alarmStatus.absorbCold.maxThreshold = ConfigManager::instance().absorbColdMaxTemp();

    alarmStatus.circuit.alarmName = "circuit";
    alarmStatus.circuit.minThreshold = ConfigManager::instance().circuitMinTemp();
    alarmStatus.circuit.maxThreshold = ConfigManager::instance().circuitMaxTemp();

    alarmStatus.dewar.alarmName = "dewar";
    alarmStatus.dewar.minThreshold = ConfigManager::instance().dewarMinTemp();
    alarmStatus.dewar.maxThreshold = ConfigManager::instance().dewarMaxTemp();

    alarmStatus.backup1.alarmName = "backup1";
    alarmStatus.backup1.minThreshold = ConfigManager::instance().backup1MinTemp();
    alarmStatus.backup1.maxThreshold = ConfigManager::instance().backup1MaxTemp();

    alarmStatus.backup2.alarmName = "backup2";
    alarmStatus.backup2.minThreshold = ConfigManager::instance().backup2MinTemp();
    alarmStatus.backup2.maxThreshold = ConfigManager::instance().backup2MaxTemp();

    alarmStatus.output.alarmName = "output";
    alarmStatus.output.minThreshold = ConfigManager::instance().outputMin();
    alarmStatus.output.maxThreshold = ConfigManager::instance().outputMax();

    // 真空报警
    alarmStatus.vacuum.alarmName = "Vacuum";
    alarmStatus.vacuum.minThreshold = ConfigManager::instance().vacuumMin();
    alarmStatus.vacuum.maxThreshold = ConfigManager::instance().vacuumMax();

    // 电流报警
    alarmStatus.current.alarmName = "Current";
    alarmStatus.current.minThreshold = ConfigManager::instance().currentMin();
    alarmStatus.current.maxThreshold = ConfigManager::instance().currentMax();

    LOG_ALARM(QString("CCD1 Thresholds: Min=%1, Max=%2").arg(alarmStatus.ccd1.minThreshold).arg(alarmStatus.ccd1.maxThreshold));
    LOG_ALARM(QString("CCD2 Thresholds: Min=%1, Max=%2").arg(alarmStatus.ccd2.minThreshold).arg(alarmStatus.ccd2.maxThreshold));
    LOG_ALARM(QString("CCD3 Thresholds: Min=%1, Max=%2").arg(alarmStatus.ccd3.minThreshold).arg(alarmStatus.ccd3.maxThreshold));
    LOG_ALARM(QString("CCD4 Thresholds: Min=%1, Max=%2").arg(alarmStatus.ccd4.minThreshold).arg(alarmStatus.ccd4.maxThreshold));
    LOG_ALARM(QString("BASE1 Thresholds: Min=%1, Max=%2").arg(alarmStatus.base1.minThreshold).arg(alarmStatus.base1.maxThreshold));
    LOG_ALARM(QString("BASE2 Thresholds: Min=%1, Max=%2").arg(alarmStatus.base2.minThreshold).arg(alarmStatus.base2.maxThreshold));
    LOG_ALARM(QString("Vacuum Thresholds: Min=%1, Max=%2").arg(alarmStatus.vacuum.minThreshold).arg(alarmStatus.vacuum.maxThreshold));
    //LOG_ALARM(QString("CCD1 Thresholds: Min=%1, Max=%2").arg(alarmStatus.ccd1.minThreshold).arg(alarmStatus.ccd1.maxThreshold));
}
/*
void MainWindow::updateAlarmUI()
{
    qDebug() << "Updating alarm UI...";
    auto alarms = alarmStatus.allAlarms();

    for (auto it = alarms.begin(); it != alarms.end(); ++it) {
        QLabel* label = findChild<QLabel*>("label" + it.key());
        if (label) {
            if (it.value()->isAlarming) {
                label->setStyleSheet("color: red; font-weight: bold;");
            } else if (it.value()->thresholdExceeded) {
                label->setStyleSheet("color: orange;");
            } else {
                label->setStyleSheet("");
            }
        }
    }

    // 全局报警状态灯
    bool anyAlarm = std::any_of(alarms.begin(), alarms.end(),
                                [](const auto& alarm) { return alarm->isAlarming; });

    ui->labelGlobalAlarm->setText(anyAlarm ? "ALARM" : "NORMAL");
    ui->labelGlobalAlarm->setStyleSheet(
        QString("background-color: %1; color: white;").arg(anyAlarm ? "red" : "green"));
}*/
void MainWindow::updateAlarmUI() {
    auto alarms = alarmStatus.allAlarms();
    bool anyAlarm = false;

    for (auto it = alarms.begin(); it != alarms.end(); ++it) {
        if (it.value()->isAlarming) {
            anyAlarm = true;
            break;  // 发现一个报警即可终止循环
        }
    }

    LOG_ALARM(QString("Global alarm update - AnyAlarm:%1").arg(anyAlarm));
    ui->labelGlobalAlarm->setText(anyAlarm ? "ALARM" : "NORMAL");
    ui->labelGlobalAlarm->setStyleSheet(
        QString("background-color: %1; color: white;").arg(anyAlarm ? "red" : "green"));
}

QString MainWindow::getAlarmReason(const QString& alarmName)
{
    auto alarm = alarmStatus.allAlarms()[alarmName];
    QString direction = alarm->currentValue < alarm->minThreshold ? "低于" : "高于";
    return QString("%1 %2阈值 (当前: %3, 范围: [%4, %5])")
        .arg(alarmName)
        .arg(direction)
        .arg(alarm->currentValue)
        .arg(alarm->minThreshold)
        .arg(alarm->maxThreshold);
}
int MainWindow::getModuleCode(const QString& alarmName)
{
    static QMap<QString, int> moduleMap = {
        {"Vacuum", 1},
        {"Current", 2},
        {"CCD1", 4},
        {"CCD2", 4}, // ...所有温度传感器
        {"Other", 8}
    };
    return moduleMap.value(alarmName, 8);
}

void MainWindow::sendRecoveryToServer(const QString& alarmName)
{
    // 显示恢复信息
    QString status = QString("%1 已恢复正常").arg(alarmName);
    ui->alarmInfoText->append(status);

    QJsonObject recoveryData;
    recoveryData["status"] = 1; // 正常状态
    recoveryData["module"] = getModuleCode(alarmName);
    recoveryData["reason"] = QString("%1 恢复正常范围").arg(alarmName);
    recoveryData["timestamp"] = QDateTime::currentDateTime().toString(Qt::ISODate);

    // ...发送POST请求（同sendAlarmToServer）
}
